package com.zwt.controller;

import com.alibaba.fastjson.JSONObject;
import com.zwt.constant.RedisConstant;
import com.zwt.constant.RedisKeyUtil;
import com.zwt.model.TAccountUser;
import com.zwt.model.TSysDict;
import com.zwt.redis.Redis;
import com.zwt.redis.TRedis;
import com.zwt.result.ResultBean;
import com.zwt.result.ResultCode;
import com.zwt.service.TAccountUserService;
import com.zwt.service.TSysDictService;
import com.zwt.util.TRegular;
import com.zwt.util.TString;
import com.zwt.util.TTime;
import com.zwt.util.sms.MessageUtil;
import com.zwt.util.sms.Phone;
import com.zwt.util.sms.TSMS;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created by zwt on 2018/9/6.
 * 短信发送
 */
@RestController
@RequestMapping("/baseServer/sms")
public class SmsController {


    private static Logger logger = LoggerFactory.getLogger(SmsController.class);

    @Autowired
    private TAccountUserService tAccountUserService;

    @Autowired
    private TSysDictService tSysDictService;

    @Autowired
    private Redis redis;



    /**
     * 注册发送验证码
     * @param phone
     * @return
     */
    @RequestMapping("reg")
    public ResultBean<JSONObject> reg(@RequestParam String phone){
        ResultBean<JSONObject> result = new ResultBean<>();
        if(StringUtils.isBlank(phone)){
            logger.error("用户手机号: {}, 注册时间: {}, 注册失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"手机号为空");
            result.setMessage("手机号不能为空!");
            return result;
        }
        if (!TRegular.validatePhone(phone)) {
            logger.error("用户手机号: {}, 注册时间: {}, 注册失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"手机号码格式错误");
            result.setMessage("手机号码格式错误!");
            return result;
        }
        TAccountUser tAccountUser = tAccountUserService.selectByPhone(phone);
        if(null!=tAccountUser){
            logger.error("用户手机号: {}, 注册时间: {}, 注册失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"该手机号已被注册");
            result.setMessage("该手机号已被注册!");
            return result;
        }
        String randomKey = TString.getRandom(6);
        TSysDict dict = tSysDictService.selectByPrimaryKey("t_sms_dynamic_code");
        String msg = dict.getDictStrValue();
        msg = msg.replaceAll("#dynamic_code#", randomKey);
        Phone iPhone = new Phone();
        iPhone.setFlag(true);
        iPhone.setPhone(phone);
        iPhone.setMessage(msg);
        iPhone.setRandomCode(randomKey);
        iPhone.setRandomPeriod(5 * 60);
        iPhone.setRandomRedisKey("ADMIN_NOTICE_");
        iPhone.setSendNum(10);
        iPhone.setSendNumPeriod(TTime.ONE_DAY);
        iPhone.setSendNumRedisKey("SET_ADMIN_NOTICE_");
        iPhone.setSendIntervalPeriod(1 * 60);
        iPhone.setSendIntervalPeriodKey("SET_ADMIN_NOTICE_MSG_REG");
        JSONObject data = MessageUtil.sendRandomCode(iPhone);
        if(data.get("code")!=null && data.get("code").equals(0)){
            redis.set(RedisKeyUtil.getRegCache(phone),randomKey, RedisConstant.MINUTE_1*5);
            data.put("smsCode",randomKey);
            result.setData(data);
            result.setMessage("发送成功");
            result.setResultCode(ResultCode.SUCCESS.getCode());
            return result;
        }
        result.setMessage(String.valueOf(data.get("msg")));
        return result;
    }

    /**
     * 登录发送验证码
     * @param phone
     * @return
     */
    @RequestMapping("login")
    public ResultBean<JSONObject> login(@RequestParam String phone){
        ResultBean<JSONObject> result = new ResultBean<>();
        if(StringUtils.isBlank(phone)){
            logger.error("用户手机号: {}, 登录时间: {}, 登录失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"手机号为空");
            result.setMessage("手机号不能为空!");
            return result;
        }
        if (!TRegular.validatePhone(phone)) {
            logger.error("用户手机号: {}, 登录时间: {}, 登录失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"手机号码格式错误");
            result.setMessage("手机号码格式错误!");
            return result;
        }
        TAccountUser tAccountUser = tAccountUserService.selectByPhone(phone);
        if(null==tAccountUser){
            logger.error("用户手机号: {}, 登录时间: {}, 登录失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"该手机号不存在");
            result.setMessage("该手机号不存在!");
            return result;
        }
        Byte userStatus = tAccountUser.getUserStatus();
        if(null==userStatus){
            logger.error("用户手机号: {}, 登录时间: {}, 登录失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"tAccountUser.getUserStatus()==null");
            result.setMessage("该账号不存在!");
            return result;
        }
        if(ObjectUtils.equals(userStatus.intValue(),0)){
            logger.error("用户手机号: {}, 登录时间: {}, 登录失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"tAccountUser.getUserStatus()==0");
            result.setMessage("该账号被禁用!");
            return result;
        }
        String randomKey = TString.getRandom(6);
        TSysDict dict = tSysDictService.selectByPrimaryKey("t_sms_dynamic_code");
        String msg = dict.getDictStrValue();
        msg = msg.replaceAll("#dynamic_code#", randomKey);
        Phone iPhone = new Phone();
        iPhone.setFlag(true);
        iPhone.setPhone(phone);
        iPhone.setMessage(msg);
        iPhone.setRandomCode(randomKey);
        iPhone.setRandomPeriod(5 * 60);
        iPhone.setRandomRedisKey("ADMIN_NOTICE_");
        iPhone.setSendNum(10);
        iPhone.setSendNumPeriod(TTime.ONE_DAY);
        iPhone.setSendNumRedisKey("SET_ADMIN_NOTICE_");
        iPhone.setSendIntervalPeriod(1 * 60);
        iPhone.setSendIntervalPeriodKey("SET_ADMIN_NOTICE_MSG_LOGIN");
        JSONObject data = MessageUtil.sendRandomCode(iPhone);
        if(data.get("code")!=null && data.get("code").equals(0)){
            redis.set(RedisKeyUtil.getLoginCache(phone),randomKey, RedisConstant.MINUTE_1*5);
            data.put("smsCode",randomKey);
            result.setData(data);
            result.setMessage("发送成功");
            result.setResultCode(ResultCode.SUCCESS.getCode());
            return result;
        }
        result.setMessage(String.valueOf(data.get("msg")));
        return result;
    }
}
